package myJs.cps

import myJs.Implicits._
import myJs.myPkg.jquery.{$, JQuery}
import org.scalajs.dom.html.Form
import org.scalajs.dom.{Event, html}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.{React, ReactRef}
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.web.html._

import scala.scalajs.js

/**
 * Created by yz on 21/1/2022
 */
@react object PureInputCp {

  case class Props(name: String = "", hasBv: Boolean = false, formRef: ReactRef[Form] = null,
                   readOnly: Boolean = false, placeHolder: String = "", value: js.UndefOr[String] = js.undefined,
                   onChange: js.UndefOr[String => Unit] = js.undefined, `type`: String = "text",
                   selfClassName: String = "", multiple: Boolean = false, show: Boolean = true,
                   style: js.UndefOr[Style] = js.undefined, autoComplete: String = "on")

  val component = FunctionalComponent[Props] { props =>
    val inputRef = React.createRef[html.Input]

    val (myV, setMyV) = useState("")

    useEffect(() => {
      if (props.hasBv) {
        if ($(props.formRef.current).data("bootstrapValidator").isDefined) {
          val bv = $(props.formRef.current).bv
          val inputJq = $(inputRef.current)
          if (props.show) {
            bv.revalidateField(inputJq)
          } else {
            bv.updateStatus(inputJq, "VALID")
          }
        }
      }
    }, List(props.show)
    )

    def valueChange = (e: SyntheticEvent[TagElement#RefType, Event]) => {
      val v = e.target.asInstanceOf[html.Input].value
      props.onChange.toOption match {
        case Some(f) => f(v)
        case None => setMyV(v)
      }
    }

    val v = props.value.map { x => x }.getOrElse(myV)

    input(style := props.style.getOrElse(Style()), `type` := props.`type`, className := s"form-control fillByName ${props.selfClassName}",
      name := s"${props.name}", value := s"${v}",
      readOnly := props.readOnly, placeholder := props.placeHolder, ref := inputRef, onChange := valueChange,
      multiple := props.multiple,autoComplete:=props.autoComplete
    )

  }

}
